package com.huobao.yunying.https;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huobao.yunying.activitys_log_reg.Act_Login;
import com.xrz.sxm.base.utils.ToolLoading;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.Callback;

import org.xutils.common.util.LogUtil;

import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class Http {

	private static Http m_Http;

	public static Http getInstant() {
		if (m_Http == null)
			m_Http = new Http();
		return m_Http;
	}

	private Http() {
	}


	private boolean checkNet(Context context) {
		if(context == null) return false;
		boolean isOk = false;
		ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (manager != null) {
			NetworkInfo[] networks = manager.getAllNetworkInfo();
			for (NetworkInfo network : networks) {
				NetworkInfo.State state = network.getState();
				if (NetworkInfo.State.CONNECTED == state) {
					isOk = true;
					break;
				}
			}
		}
		return isOk;
	}


	private boolean checkNet(Context context, HttpListener listener){
		boolean isNetAva = checkNet(context);
		if (!isNetAva) {
			Toast.makeText(context, "网络连接错误，请检查后重试！",Toast.LENGTH_SHORT).show();
			listener.onHttpError("网络连接错误，请检查后重试！");
		}
		return isNetAva;
	}

	public void sendRequest(final Context context, Map<String, String> map, final HttpListener listener) {
		sendRequest(context, true, map, listener);
	}

	/**
	 * 只需显示返回结果得请求
	 * 
	 * @param ctx
	 * @param map
	 */
	public void sendRequest(final Context ctx, Map<String, String> map) {
		sendRequest(ctx, true, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				Toast.makeText(ctx, jsonObject.getString("msg"), Toast.LENGTH_LONG).show();
			}

			@Override
			public void onHttpError(String error) {
			}
		});
	}

	public String sendRequestSync(Map<String, String> map) {
		PostFormBuilder builder = OkHttpUtils.post().url(HttpConst.BASEURL);
		if (map != null)
			for (Map.Entry<String, String> entry : map.entrySet()) {
				builder.addParams(entry.getKey(), entry.getValue());
			}
		try {
			Response response = builder.build().execute();
			ResponseBody body = response.body();
			return body.string();
		} catch (IOException e) {
		}
		return null;
	}
	
	public String sendRequestSync(String url,Map<String, String> map) {
		PostFormBuilder builder = OkHttpUtils.post().url(url);
		if (map != null)
			for (Map.Entry<String, String> entry : map.entrySet()) {
				builder.addParams(entry.getKey(), entry.getValue());
			}
		try {
			Response response = builder.build().execute();
			ResponseBody body = response.body();
			return body.string();
		} catch (IOException e) {
		}
		return null;
	}

	public void test(final Context context, final boolean isshowDialog, Map<String, String> map,
			final HttpListener listener) {
		if (isshowDialog)
			ToolLoading.ShowLoading(context);
		PostFormBuilder builder = OkHttpUtils.post().url(HttpConst.BASEURL);
		if (map != null)
			for (Map.Entry<String, String> entry : map.entrySet()) {
				builder.addParams(entry.getKey(), entry.getValue());
			}
		builder.build().execute(new Callback<String>() {

			@Override
			public String parseNetworkResponse(Response response) throws Exception {
				String result = response.body().string();
				return result;
			}

			@Override
			public void onError(Call request, Exception e) {

			}

			@Override
			public void onResponse(String result) {
				listener.onHttpSuccess(result);
			}
		});
	}

	public void sendRequest(final Context context, final boolean isshowDialog, final String url,
			Map<String, String> map, final HttpListener listener) {
		if(!checkNet(context, listener))return;
		if (isshowDialog)
			ToolLoading.ShowLoading(context);
		PostFormBuilder builder = OkHttpUtils.post().url(url);
		if (map != null)
			for (Map.Entry<String, String> entry : map.entrySet()) {
				String value = entry.getValue();
				if(TextUtils.isEmpty(value))continue;
				builder.addParams(entry.getKey(), entry.getValue());
			}
		if(builder == null)return;
		builder.build().execute(new com.zhy.http.okhttp.callback.Callback<String>() {

			@Override
			public String parseNetworkResponse(Response response) throws Exception {
				String result = response.body().string();
				return result;
			}

			@Override
			public void onError(Call request, Exception e) {
				if (isshowDialog)
					ToolLoading.closeLoading(context);
				Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
				listener.onHttpError(e.toString());
			}

			@Override
			public void onResponse(String result) {
				String error = checkResult(result);
				if (isshowDialog)
					ToolLoading.closeLoading(context);
				if (error.equals("")) {
					LogUtil.e(result);
					listener.onHttpSuccess(result);
				} else {
					Toast.makeText(context, error, Toast.LENGTH_SHORT).show();
					if(error.equals("请登录后操作")){
						Intent intent = new Intent(context, Act_Login.class);
						intent.putExtra("flag",true);
						context.startActivity(intent);
						return;
					}
					listener.onHttpError(error);
				}
			}
		});
	}

	public void sendRequest(final Context context, final boolean isshowDialog, Map<String, String> map,
			final HttpListener listener) {
		sendRequest(context, isshowDialog, HttpConst.BASEURL, map, listener);

	}

	private String checkResult(String result) {
		if (result == null || result.equals("null") || result.equals(""))
			return "服务器返回空，我也不知道是成功了还是失败了.............";
		try {
			JSONObject object = JSON.parseObject(result);
			return object.getBoolean("done") == true ? "" : object.getString("msg");
		} catch (Exception e) {
			return "";
		}
	}

}
